/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.command.component.serializer;

import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.caf.cef.schema.base.utils.JsonUtil;
import com.inspur.edp.web.command.component.ComponentConstant;
import com.inspur.edp.web.command.component.metadata.CommandItem;
import com.inspur.edp.web.command.component.metadata.CommandItemType;
import com.inspur.edp.web.command.component.serializer.CommandItem.CommandItemSerializerFactory;
import com.inspur.edp.web.command.component.serializer.CommandItem.ICommandItemSerializer;

/**
 * @author Kaixuan Shi
 * @version 0.1
 */
public class CommandItemSerializer {

    public static JsonNode serialize(CommandItem item) {
        CommandItemType itemType = item.getItemType();
        ICommandItemSerializer serializer = CommandItemSerializerFactory.get(itemType);
        JsonNode resultNode = serializer.serialize(item);
        //旧版结构为此，此处为兼容，可与web组确认是否可删除
        JsonUtil.setPropValue(resultNode, "Type", itemType.getValue());
        JsonUtil.setPropValue(resultNode, "Content", serializer.serialize(item));
        return resultNode;
    }

    public static CommandItem deserialize(JsonNode itemNode) {
//        CommandItemType itemType = JsonUtil.getPropValue(itemNode, ComponentConstant.CommandItemField.ITEM_TYPE, CommandItemType.class);
        //todo 旧版元数据结构，序列化了两次，前端设计器传值时，只传入了{"Type":0,"Content":{}}，暂时兼容，此部分代码需验证
        CommandItemType itemType = JsonUtil.getPropValue(itemNode, "Type", CommandItemType.class);
        if (itemType == null) {
            throw new RuntimeException("反序列化CommandItem失败，缺少类型字段" + ComponentConstant.CommandItemField.ITEM_TYPE);
        }
        ICommandItemSerializer serializer = CommandItemSerializerFactory.get(itemType);
        return serializer.deserialize(itemNode);
    }
}
